package com.finance.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Component
public class FileDownloadUtil {

    /**
     * 从URL直接下载文件到指定路径
     *
     * @param fileUrl 文件的URL
     * @param targetPath 目标保存路径
     * @return 下载后的文件路径
     */
    public String downloadFile(String fileUrl, String targetPath) {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = null;
        try {
            // 确保目标目录存在
            Path targetDir = Paths.get(targetPath).getParent();
            if (targetDir != null) {
                Files.createDirectories(targetDir);
            }

            // 创建GET请求
            getMethod = new GetMethod(fileUrl);
            getMethod.setRequestHeader("User-Agent", "Mozilla/5.0");
            
            // 执行请求
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != 200) {
                throw new RuntimeException("Failed to download file, HTTP status code: " + statusCode);
            }

            // 下载文件
            try (InputStream inputStream = getMethod.getResponseBodyAsStream();
                 FileOutputStream outputStream = new FileOutputStream(targetPath)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            log.info("Successfully downloaded file to: {}", targetPath);
            return targetPath;
        } catch (Exception e) {
            log.error("Failed to download file from URL: {}", fileUrl, e);
            throw new RuntimeException("Failed to download file", e);
        } finally {
            if (getMethod != null) {
                getMethod.releaseConnection();
            }
        }
    }
} 